{% extends "layout.html" %}

{% block body %}

<div id="ajaxImage" style="display: inline;"><img src="{{ url_for('static', filename='AjaxLoading.gif') }}" /></div>
<div id="statusDiv"></div>
<div id="progressbar" style="height: 20px; width: 200px;"></div>

<div class="panel panel-default " style="margin-left: 20px;margin-top: 40px;width: 800px">
<div style="margin:5px;">
<span class=" glyphicon glyphicon-info-sign"></span> 警告：这是一个异步处理进程。<br>
你可以:
<ul><li>打开另一个选项卡或窗口，继续在Ecotaxa中工作（并不时切换到此页面，监视任务进程）
<li>离开此页，继续在Ecotaxa中工作（点击Ecotaxa 顶端右上角的“Run”或“Done”按钮，来监视任务进度或检查其完成情况）
</ul>
异步处理常用于可能耗时较长的进程，它可以创建临时数据（例如导出文件），这些数据可以在流程结束时手动删除，即使Ecotaxa在定期为您执行操作。其余任务可以使用右上角的“Done”or“Error”按钮进行检查。

</div>
</div>
<script>

function StartMonitor(TaskID)
{
    var $ajaxImage = $("#ajaxImage");
    var $progressbar = $("#progressbar");
    var $statusDiv = $("#statusDiv");
    var $StopTimer=false;
  {#  Set up a recurring timer to keep running this code every second
      We use intervalHandle later via clearInterval to turn off this timer  #}
        intervalHandle = setInterval(function () {
          {% if RedirectToMonitor %} {# Permet passer de la page de création à la page de Monitor pour éviter les créations multiples en cas de refresh pas l'utilisateur. #}
            window.location="/Task/Monitor/"+TaskID;
            return;
          {% endif %}
            // Go hit the web service to get the latest status
            $.ajax({
                type: "GET",
                dataType: "json",
                url: "/Task/GetStatus/"+TaskID,
                //data:{TaskID:TaskID,Action:'GetStatus'},
                contentType: "application/json; charset=utf-8",
                success: function (response, status, xhr) {
{# $StopTimer permet de traiter le fait qu'il y a parfois un timer de 1s coté serveur pour laisser la tache se finir,
et du coup une seconde requete ajax est emise par le client et retourne le fait que la tache n'existe plus plutot que l'affichage prevu #}
                    if($StopTimer) return;
                    if (response.d != null) {
                        // We're running and have status - so:

                        // Show the AJAX spinner image and progress bar
                        $ajaxImage.show();
                        $progressbar.show();

                        // Set the status text and the progress back value
                        $statusDiv.html(response.d.PercentComplete + "% " + response.d.WorkDescription);
                        $progressbar.progressbar({
                            value: response.d.PercentComplete
                        });

                        // Process is complete, start to reset the UI (the response.d == null above, will do the rest).
                        if (response.d.IsComplete) {
                            $StopTimer=true;
                            $statusDiv.html('<div class="alert alert-success" role="alert">任务完成 :'+response.d.WorkDescription+'<br>  '+ response.d.ExtraAction +'</div>');
                            $ajaxImage.hide();
                            $progressbar.hide();
                            clearInterval(intervalHandle);
                        }
                        if (response.d.IsError) {
                            $StopTimer=true;
                            $statusDiv.html('<div class="alert alert-danger" role="alert">' +
                                '<div style="display: inline-block;margin-right: 30px;max-height:500px;overflow:auto;">'
                                +response.d.WorkDescription+'</div><a href="/Task/Show/{{ TaskID }}" class="btn btn-primary btn-sm " role="button">Show Task</a></div>');
                            $ajaxImage.hide();
                            $progressbar.hide();
                            clearInterval(intervalHandle);
                        }
                    }
                    else if (response.q != null) {
                        $StopTimer=true;
                        // Redirection vers question
                        $statusDiv.html('<div class="alert alert-warning" role="alert">'+response.q.Message+' <a href="'+response.q.Url+'" class="btn btn-primary btn-sm " role="button">Go</a></div>');
                        $ajaxImage.hide();
                        $progressbar.hide();
                        clearInterval(intervalHandle);
                    }
                    else {
                        $StopTimer=true;
                        // The background process isn't running or there was a problem - reset.
                        $statusDiv.html("?");

                        // Stop this setInterval loop that we're in.
                        clearInterval(intervalHandle);
                        $ajaxImage.hide();
                        $progressbar.hide();
                    }
                }
            });

        }, 1000);
}
// Wait until the DOM is loaded
$().ready(function () {

    // Go get handles to the UI elements that we need.
    var $ajaxImage = $("#ajaxImage");
    var $progressbar = $("#progressbar");
    var $statusDiv = $("#statusDiv");

    // Hide the AJAX spinner image and the progress bar, by default.
    $ajaxImage.hide();
    $progressbar.hide();

    // Turn off AJAX caching. When we make an AJAX call, we always want the latest.
    //$.ajaxSetup({ cache: false });

    // Simple error handling. If an AJAX error occurs, it wil show in our statusDiv.
    $(document).ajaxError(function (e, jqxhr, settings, exception) {
        $statusDiv.html("Error from AJAX call: " + jqxhr.statusText);
    });
    StartMonitor({{ TaskID }});
});
</script>
{% endblock %}